package com.yhsoft.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yhsoft.buyer.entity.BuyerUser;
import com.yhsoft.buyer.service.IBuyerUserService;
import com.yhsoft.common.service.Po.TokenUser;
import com.yhsoft.common.service.TokenService;
import com.yhsoft.goods.entity.GoodsInfo;
import com.yhsoft.goods.service.IGoodsInfoService;
import com.yhsoft.sys.controller.Response.WorkOrderDetailOutVo;
import com.yhsoft.sys.controller.Response.WorkOrderInfoOutVo;
import com.yhsoft.sys.controller.request.AddWorkOrderInVo;
import com.yhsoft.sys.controller.request.DealWorkOrderInVo;
import com.yhsoft.sys.controller.request.SendWorkOrderInVo;
import com.yhsoft.sys.controller.request.WorkOrderQuery;
import com.yhsoft.sys.entity.CompanyInfo;
import com.yhsoft.sys.entity.User;
import com.yhsoft.sys.entity.WorkOrderInfo;
import com.yhsoft.sys.mapper.WorkOrderInfoMapper;
import com.yhsoft.sys.service.ICompanyInfoService;
import com.yhsoft.sys.service.IMessageService;
import com.yhsoft.sys.service.IUserService;
import com.yhsoft.sys.service.IWorkOrderInfoService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;

/**
 * <p>
 * 工单信息表 服务实现类
 * </p>
 *
 * @author yyyyyyyh
 * @since 2023-11-20
 */
@Service
public class WorkOrderInfoServiceImpl extends ServiceImpl<WorkOrderInfoMapper, WorkOrderInfo> implements IWorkOrderInfoService {

    @Resource
    private IBuyerUserService iBuyerUserService;

    @Resource
    private ICompanyInfoService companyInfoService;

    @Resource
    private IGoodsInfoService iGoodsInfoService;

    @Resource
    private IMessageService iMessageService;

    @Resource
    private IUserService userService;

    @Override
    public String add(AddWorkOrderInVo inVo) {
        LambdaQueryWrapper<WorkOrderInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WorkOrderInfo::getOrderNo, inVo.getOrderNo());
        queryWrapper.eq(WorkOrderInfo::getProgress, 0);
        if (this.getBaseMapper().exists(queryWrapper)) {
            return "该订单存在处理中的工单，无法重复新增！";
        }

        WorkOrderInfo workOrderInfo = new WorkOrderInfo();
        BeanUtils.copyProperties(inVo, workOrderInfo);
        workOrderInfo.setCreateTime(LocalDateTime.now());
        workOrderInfo.setPromoterId(TokenService.getUserBytoken().getId());
        workOrderInfo.setDistributorId(TokenService.getUserBytoken().getCompanyId());
        // 设置为未分发
        workOrderInfo.setStatus(0);
        // 设置为处理中
        workOrderInfo.setProgress(0);

        // 设置商品图片
        GoodsInfo goodsInfo = iGoodsInfoService.getById(inVo.getGoodsId());
        if (goodsInfo == null) {
            return "获取商品信息失败！";
        }

        workOrderInfo.setGoodsId(goodsInfo.getId());
        workOrderInfo.setGoodsPic(goodsInfo.getPicUrl());

        this.getBaseMapper().insert(workOrderInfo);

        // 添加平台消息
        iMessageService.addSysWorkOrderNews(workOrderInfo.getId(), workOrderInfo.getDistributorId());
        return "success";
    }

    @Override
    public IPage<WorkOrderInfoOutVo> getList(WorkOrderQuery inVo, Long pageNo, Long pageSize) {
        QueryWrapper<WorkOrderInfoOutVo> queryWrapper = new QueryWrapper<>();

        // 判断是哪个端
        TokenUser user = TokenService.getUserBytoken();
        if(user.getSysType().equals("saler")){
            queryWrapper.eq("a.distributor_id", TokenService.getUserBytoken().getCompanyId());
        } else if (user.getSysType().equals("vender")) {
            queryWrapper.eq("a.vender_id", TokenService.getUserBytoken().getCompanyId());
            queryWrapper.eq("a.status", 1);
        }

        queryWrapper.like(StringUtils.hasLength(inVo.getOrderNo()), "a.order_no", inVo.getOrderNo());
        queryWrapper.like(StringUtils.hasLength(inVo.getGoodsName()), "a.goods_name", inVo.getGoodsName());
        queryWrapper.eq(inVo.getOrderType() != null, "a.order_type", inVo.getOrderType());
        queryWrapper.eq(inVo.getProgress() != null, "a.progress", inVo.getProgress());
        queryWrapper.like(StringUtils.hasLength(inVo.getVenderName()), "c.company_name", inVo.getVenderName());
        queryWrapper.like(StringUtils.hasLength(inVo.getDistributorName()), "d.company_name", inVo.getDistributorName());

        queryWrapper.ge((inVo.getStartTime() != null), "a.create_time", inVo.getStartTime());
        if (inVo.getEndTime() != null) {
            queryWrapper.le( "a.create_time", LocalDateTime.of(inVo.getEndTime(), LocalTime.MAX));
        }

        Page<WorkOrderInfoOutVo> page = new Page<>(pageNo, pageSize);
        IPage<WorkOrderInfoOutVo> iPage = baseMapper.getList(page, queryWrapper);

        return iPage;
    }

    @Override
    public WorkOrderDetailOutVo getWorkOrderdetil(String workOrderId) {
        WorkOrderInfo workOrderInfo = baseMapper.selectById(workOrderId);
        WorkOrderDetailOutVo outVo = new WorkOrderDetailOutVo();
        BeanUtils.copyProperties(workOrderInfo, outVo);

        BuyerUser buyerUser = iBuyerUserService.getById(workOrderInfo.getCustomerId());
        if(buyerUser != null){
            outVo.setNickName(buyerUser.getNickName());
            outVo.setPhone(buyerUser.getPhone());
        }

        CompanyInfo companyInfo = companyInfoService.getById(workOrderInfo.getVenderId());
        if(companyInfo != null){
            outVo.setVenderName(companyInfo.getCompanyName());
        }

        CompanyInfo companyInfo1 = companyInfoService.getById(workOrderInfo.getDistributorId());
        if(companyInfo1 != null){
            outVo.setDistributorName(companyInfo1.getCompanyName());
        }

        User user = userService.getById(workOrderInfo.getPromoterId());
        if(user != null){
            outVo.setPromoterName(user.getName());
        }

        return outVo;
    }

    @Override
    public String send(SendWorkOrderInVo inVo) {
        WorkOrderInfo workOrderInfo = baseMapper.selectById(inVo.getId());

        if(inVo.getProgress() != null){
            workOrderInfo.setProgress(inVo.getProgress());
            if(inVo.getProgress() == 1){
                // 发送消息
                iMessageService.addSalerWorkOrderNews(workOrderInfo.getId(), workOrderInfo.getDistributorId());
            }
        }
        if(StringUtils.hasLength(inVo.getPlatformRemark())){
            workOrderInfo.setPlatformRemark(inVo.getPlatformRemark());
            workOrderInfo.setPlatformRemarkTime(LocalDateTime.now());
        }

        // 设置分发状态，0是默认，1供货商可见
        workOrderInfo.setStatus(1);
        this.getBaseMapper().updateById(workOrderInfo);

        // 发送消息
        iMessageService.addVenderWorkOrderNews(workOrderInfo.getId(), workOrderInfo.getVenderId());

        return "success";
    }

    @Override
    public String deal(DealWorkOrderInVo inVo) {
        WorkOrderInfo workOrderInfo = baseMapper.selectById(inVo.getId());

        // 设置备注信息
        workOrderInfo.setVenderRemark(inVo.getVenderRemark());
        workOrderInfo.setVenderRemarkTime(LocalDateTime.now());

        this.getBaseMapper().updateById(workOrderInfo);

        return "success";
    }
}
